<?php
/**
 * IndexController
 * 
 * @author
 * @version 
 */
require_once 'Zend/Controller/Action.php';
class IndexController extends Thaind_Controller_Action
{
	var $_arrParam;
    public function init()
    {

//    	Truyá»�n tham sá»‘ ra view

    	$this->_arrParam = $this->_request->getParams();
    	$this->view->arrParam = $this->_arrParam;
    }

    public function preDispatch(){
    }
    
    public function indexAction(){
    }
	   public function loginAction (){
        //		Load css
        //		Load các model và form sử dụng trong action
        Zend_Loader::loadClass('Default_Forms_LoginForm');
        Zend_Loader::loadClass('Default_Models_LoginModel');
        //		Khởi tạo biến
        $form = new Default_Forms_LoginForm();
        $model = new Default_Models_LoginModel();
        if ($this->_request->isPost()) {
            if ($form->isValid($this->_arrParam)) {
                if ($model->login($this->_arrParam)) {
                    $this->_redirect("/");
                } else {
                    echo '<div class="row"><div class="col-xs-6 col-xs-push-3"><div class = "alert alert-danger"><center>Đăng nhập không thành công</center></div></div></div>';
                }
            }
        }
        //		Truyền biến ra view
        $this->view->form = $form;
    }
    public function facebookLoginAction (){
    	
    	$this->_helper->viewRenderer->setNoRender();
//    	Load model sử dụng trong action

    	Zend_Loader::loadClass("Default_Models_UserModel");

//    	Khai báo biến

    	$user_model = new Default_Models_UserModel();
    	
//    	Lấy access token từ facebook

    	$client = new Zend_Http_Client("https://graph.facebook.com/oauth/access_token");
    	$client->setParameterGet(array("client_id"		=> FACEBOOK_APP_ID,
    									"client_secret"	=> FACEBOOK_SECRET,
    									"redirect_uri"	=> HOMEPAGE . "/index/facebook-login",
    									"code"			=> $this->_arrParam['code'],
    	));
    	try {
	    	$body = $client->request()->getBody();
	    	$access_token = explode("&", $body);
	    	$access_token = str_replace('access_token=', '', $access_token[0]);
	    	
//	    	Lấy thông tin user

	    	$graph_client = new Zend_Http_Client("https://graph.facebook.com/me");
	    	$graph_client->setParameterGet(array("access_token"		=> $access_token));
	    	
	    	$graph_body = $graph_client->request()->getBody();
	    	$facebook_user_info = Zend_Json::decode($graph_body);
	    	
//	    	Lưu thông tin đăng nhập vào session

	    	if (isset($facebook_user_info['id'])){
	    		$user_info = $user_model->getUserInfoByUsername("facebook_" . $facebook_user_info['id']);
    			$auth = Thaind_Auth_User::getInstance();
	    		if ($user_info){
	    			$auth->getStorage()->write((object)$user_info);
	    			Zend_Session::start();
	    		}else{
	    			$data = array("status"			=> 1,
	    							"active"		=> 1,
	    							"username"		=> "facebook_" . $facebook_user_info['id'],
	    							"first_name"	=> $facebook_user_info['first_name'],
	    							"last_name"		=> $facebook_user_info['last_name'],
	    							"password"		=> sha1($facebook_user_info['id']),
	    							"email"			=> $facebook_user_info['email'],
	    			);
	    			try {
		    			$id = $user_model->insert($data);
		    			$data['id'] = $id;
		    			unset($data['status']);
		    			unset($data['active']);
		    			unset($data['password']);
		    			$auth->getStorage()->write((object)$data);
		    			Zend_Session::start();
	    			} catch (Exception $e) {
	    			}
	    		}
	    	}
    		$this->_redirect("/");
    	} catch (Exception $e) {
    	}
    	
    }
    public function googleLoginAction (){
    	
    	$this->_helper->viewRenderer->setNoRender();
//    	Load model sử dụng trong action

    	Zend_Loader::loadClass("Default_Models_UserModel");

//    	Khai báo biến

    	$user_model = new Default_Models_UserModel();
    	
    	$tocken_client = new Zend_Http_Client("https://accounts.google.com/o/oauth2/token");
    	$tocken_client->setParameterPost(array("code"			=> $this->_arrParam['code'],
    											"client_id"		=> GOOGLE_APP_ID,
    											"client_secret"	=> GOOGLE_SECRET,
    											"redirect_uri"	=> HOMEPAGE . "/index/google-login",
    											"grant_type"	=> "authorization_code",
    	));
    	try {
	    	$tocken_body = Zend_Json::decode($tocken_client->request("POST")->getBody());
    		if ($tocken_body['access_token']){
    			$segments = explode(".", $tocken_body['id_token']);
    			if (count($segments) == 3){
	    			$google_user_info = Zend_Json::decode(base64_decode($segments[1]));
	    			if ($google_user_info){
	    				
			    		$user_info = $user_model->getUserInfoByUsername("google_" . $google_user_info['sub']);
		    			$auth = Thaind_Auth_User::getInstance();
			    		if ($user_info){
			    			$auth->getStorage()->write((object)$user_info);
			    			Zend_Session::start();
			    		}else{
		    				
		    				$google_profile_client = new Zend_Http_Client("https://www.googleapis.com/oauth2/v1/userinfo");
		    				$google_profile_client->setParameterGet(array("alt"	=> "json",
		    																"access_token"	=> $tocken_body['access_token']
		    				));
		    				
		    				$google_profile_body = Zend_Json::decode($google_profile_client->request()->getBody());
		    				
			    			$data = array("status"			=> 1,
			    							"active"		=> 1,
			    							"username"		=> "google_" . $google_user_info['sub'],
			    							"first_name"	=> $google_profile_body['given_name'],
			    							"last_name"		=> $google_profile_body['family_name'],
			    							"password"		=> sha1($google_user_info['sub']),
			    							"email"			=> $google_user_info['email'],
			    			);
			    			try {
				    			$id = $user_model->insert($data);
				    			$data['id'] = $id;
				    			unset($data['status']);
				    			unset($data['active']);
				    			unset($data['password']);
				    			$auth->getStorage()->write((object)$data);
				    			Zend_Session::start();
			    			} catch (Exception $e) {
			    			}
			    		}
			    	}
    			}
    		}
    	} catch (Exception $e) {
    	}
    	$this->_redirect("/");
    }
    public function logoutAction ()
    {
        $auth = Thaind_Auth_User::getInstance();
        $auth->clearIdentity();
        $this->_redirect('/');
    }
}
